package com.example.concurrentprogramming8016.threadpool;


import cn.hutool.Hutool;
import cn.hutool.core.date.DateUtil;

import java.util.*;
import java.util.concurrent.*;

/**
 * @author liyanhao
 * @Date 2022-12-25 14:50
 */
public class ThreadPoolTest {
    public static void main(String[] args) throws Exception {
        //单个线程的线程池
        //extracted();
        //自定义线程池
        //extracted1();
        //创建一个线程池，可以安排命令在给定的延迟后运行，或定期执行。
        extracted2();

    }

    private static void extracted2() {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
        ScheduledFuture<?> schedule = scheduledExecutorService.schedule(() -> {
            System.out.println("你好!");
            System.out.println(DateUtil.now());
        }, 10, TimeUnit.SECONDS);
        scheduledExecutorService.shutdown();
    }

    private static void extracted1() {
        final Random random = new Random();
        List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>());
        Vector<Integer> vector = new Vector<Integer>();
        LinkedBlockingQueue<Runnable> linkedBlockingQueue = new LinkedBlockingQueue<>(1);
        final Integer[] count = {0};
        ExecutorService executorService = new ThreadPoolExecutor(
                10, 15,
                0L, TimeUnit.MILLISECONDS, linkedBlockingQueue, new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                //执行拒绝的进行计数
                count[0]++;
            }
        });
        //必须要捕获异常  不然被拒绝的线程就不知道了
        try {
            for (int i = 0; i < 10000; i++) {
                executorService.execute(() -> {
                    list.add(random.nextInt());
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        executorService.shutdown();
        boolean b = false;
        try {
            b = executorService.awaitTermination(1, TimeUnit.DAYS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(b);

        System.out.println(list.size());
        System.out.println(linkedBlockingQueue.size());
        System.out.println(count[0]);
    }

    private static void extracted() throws InterruptedException {
        final Random random = new Random();
        ArrayList<Integer> list = new ArrayList<>();
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 10000; i++) {
            executorService.execute(() -> {
                list.add(random.nextInt());
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.DAYS);
        System.out.println(list.size());
    }
}
